package util;

import javax.faces.application.NavigationHandler;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;
import javax.servlet.http.HttpSession;

public class AuthorizationListener implements PhaseListener {

    @Override
    public void afterPhase(PhaseEvent event) {
        FacesContext facesContext = event.getFacesContext();
        String paginaAtual = facesContext.getViewRoot().getViewId();
        boolean ehPaginaDeLogin = (paginaAtual.lastIndexOf("login.xhtml") > -1);
        HttpSession sessao = (HttpSession) facesContext.getExternalContext().getSession(true);
        Object usuario = sessao.getAttribute("usuario");

        if (!ehPaginaDeLogin && usuario == null) {
            NavigationHandler navigationHandler = facesContext.getApplication().getNavigationHandler();
            navigationHandler.handleNavigation(facesContext, null, "/views/login.xhtml");
        }
    }

    @Override
    public void beforePhase(PhaseEvent event) {
    }

    @Override
    public PhaseId getPhaseId() {
        return PhaseId.RESTORE_VIEW;
    }

}
